/**
 * 聊天房间工具函数
 * 用于房间ID生成、解析等操作
 */

/**
 * 生成房间ID
 * 格式：患者ID_医生ID
 * @param {string} patientId - 患者ID
 * @param {string} doctorId - 医生ID
 * @returns {string} 房间ID
 */
function generateRoomId(patientId, doctorId) {
  if (!patientId || !doctorId) {
    throw new Error('患者ID和医生ID不能为空');
  }
  return `${patientId}_${doctorId}`;
}

/**
 * 从房间ID解析出患者ID和医生ID
 * @param {string} roomId - 房间ID
 * @returns {object} { patientId, doctorId }
 */
function parseRoomId(roomId) {
  if (!roomId || typeof roomId !== 'string') {
    throw new Error('房间ID格式错误');
  }
  
  const parts = roomId.split('_');
  if (parts.length !== 2) {
    throw new Error('房间ID格式错误，应为：患者ID_医生ID');
  }
  
  return {
    patientId: parts[0],
    doctorId: parts[1]
  };
}

/**
 * 验证房间ID格式
 * @param {string} roomId - 房间ID
 * @returns {boolean} 是否有效
 */
function validateRoomId(roomId) {
  try {
    const { patientId, doctorId } = parseRoomId(roomId);
    return !!(patientId && doctorId);
  } catch (error) {
    return false;
  }
}

/**
 * 根据用户类型和ID生成房间ID
 * @param {string} userId1 - 用户1 ID
 * @param {string} userType1 - 用户1 类型
 * @param {string} userId2 - 用户2 ID  
 * @param {string} userType2 - 用户2 类型
 * @returns {string} 房间ID
 */
function generateRoomIdFromUsers(userId1, userType1, userId2, userType2) {
  let patientId, doctorId;
  
  if (userType1 === 'patient' && userType2 === 'doctor') {
    patientId = userId1;
    doctorId = userId2;
  } else if (userType1 === 'doctor' && userType2 === 'patient') {
    patientId = userId2;
    doctorId = userId1;
  } else {
    throw new Error('房间只能在医生和患者之间创建');
  }
  
  return generateRoomId(patientId, doctorId);
}

/**
 * 检查用户是否属于指定房间
 * @param {string} roomId - 房间ID
 * @param {string} userId - 用户ID
 * @param {string} userType - 用户类型
 * @returns {boolean} 是否属于房间
 */
function isUserInRoom(roomId, userId, userType) {
  try {
    const { patientId, doctorId } = parseRoomId(roomId);
    
    if (userType === 'patient') {
      return patientId === userId;
    } else if (userType === 'doctor') {
      return doctorId === userId;
    }
    
    return false;
  } catch (error) {
    return false;
  }
}

/**
 * 获取房间中的另一个用户ID
 * @param {string} roomId - 房间ID
 * @param {string} currentUserId - 当前用户ID
 * @param {string} currentUserType - 当前用户类型
 * @returns {string} 另一个用户ID
 */
function getOtherUserId(roomId, currentUserId, currentUserType) {
  const { patientId, doctorId } = parseRoomId(roomId);
  
  if (currentUserType === 'patient' && currentUserId === patientId) {
    return doctorId;
  } else if (currentUserType === 'doctor' && currentUserId === doctorId) {
    return patientId;
  }
  
  throw new Error('用户不属于此房间');
}

module.exports = {
  generateRoomId,
  parseRoomId,
  validateRoomId,
  generateRoomIdFromUsers,
  isUserInRoom,
  getOtherUserId
};